package com.basic.boot.interceptor;

import com.basic.boot.common.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cherrish
 * @time 2019-03-14 10:18
 * @name WebLogInterceptor
 * @desc:
 */
@Slf4j
public class WebLogInterceptor extends HandlerInterceptorAdapter {
    private final String ACCESS_LOG = "ACCESS_LOG=>";
    private final String SEPARATOR = "|";
    private final ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        startTime.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long totalTime = System.currentTimeMillis() - startTime.get();
        int status = response.getStatus();
        StringBuilder sb = new StringBuilder(ACCESS_LOG);
        sb.append(SEPARATOR);
        sb.append(request.getMethod()).append(SEPARATOR);
        sb.append(status).append(SEPARATOR);
        sb.append(IpUtils.getRealIP(request)).append(SEPARATOR);
        sb.append(totalTime).append(SEPARATOR);
        sb.append(request.getRequestURI()).append(SEPARATOR);
        log.warn(sb.toString());
    }
}
